package com.developer.platform.domain.factory;

import com.developer.platform.domain.service.ILoginService;
import com.developer.platform.infrastructure.enums.LoginType;
import com.developer.platform.infrastructure.error.LoginErrorType;
import com.veeker.core.exceptions.BusinessException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2020-11-09
 */
@Component
public class LoginFactory implements ApplicationContextAware {

    private static Map<LoginType, ILoginService> LOGIN_MAP;

    public ILoginService handle(LoginType type) {
        ILoginService loginService = LOGIN_MAP.get(type);
        BusinessException.isNull(loginService, LoginErrorType.LOGIN_TYPE_ERROR);
        return loginService;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ILoginService> beansOfType = applicationContext.getBeansOfType(ILoginService.class);
        LOGIN_MAP = new HashMap<>(beansOfType.size());
        beansOfType.forEach((k,v)->{ LOGIN_MAP.put(v.only(),v); });
    }

}
